const appointmentService = require('../../../services/appointment');
const consultService = require('../../../services/consult');
const util = require('../../../utils/util');

Page({
  data: {
    staffInfo: null,
    statistics: {
      todayAppointments: 0,
      pendingAppointments: 0,
      totalConsultations: 0,
      activeConsultations: 0
    },
    todayAppointments: [],
    recentConsultations: [],
    loading: true
  },

  onLoad: function (options) {
    this.loadStaffInfo();
    this.loadStatistics();
    this.loadTodayAppointments();
    this.loadRecentConsultations();
  },

  onShow: function () {
    if (this.data._isShown) {
      this.refresh();
    }
    this.data._isShown = true;
  },

  // 刷新所有数据
  refresh: function () {
    this.loadStatistics();
    this.loadTodayAppointments();
    this.loadRecentConsultations();
  },

  // 加载医生信息
  loadStaffInfo: function () {
    const app = getApp();
    const staffInfo = app.getStaffInfo();
    if (staffInfo) {
      this.setData({
        staffInfo
      });
      
      // 如果没有科室名称但有科室ID，从服务器获取科室列表进行匹配
      if (staffInfo.departmentId && !staffInfo.department) {
        this.loadDepartmentInfo(staffInfo.departmentId);
      }
    } else {
      // 如果没有医生信息，返回登录页
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/login/staff-login',
        });
      }, 1500);
    }
  },
  
  // 加载科室信息
  loadDepartmentInfo: function(departmentId) {
    const staffService = require('../../../services/staff');
    staffService.getDepartments()
      .then(res => {
        const departments = Array.isArray(res) ? res : (res.records || []);
        const department = departments.find(item => item.id === departmentId);
        if (department) {
          // 更新本地显示
          this.setData({
            'staffInfo.department': department.name
          });
          
          // 更新全局数据
          const app = getApp();
          const staffInfo = app.getStaffInfo();
          if (staffInfo) {
            staffInfo.department = department.name;
            app.globalData.staffInfo = staffInfo;
            wx.setStorageSync('staffInfo', staffInfo);
          }
        }
      })
      .catch(err => {
        console.error('获取科室信息失败', err);
      });
  },

  // 加载统计数据
  loadStatistics: function () {
    const staffId = this.data.staffInfo ? this.data.staffInfo.id : null;
    if (!staffId) return;

    wx.showLoading({
      title: '加载中...',
    });

    // 获取预约统计
    appointmentService.getStaffAppointmentStatistics(staffId)
      .then(res => {
        this.setData({
          'statistics.todayAppointments': res.todayCount || 0,
          'statistics.pendingAppointments': res.pendingCount || 0
        });
      })
      .catch(err => {
        console.error('获取预约统计失败', err);
        // 设置默认值，避免UI显示错误
        this.setData({
          'statistics.todayAppointments': 0,
          'statistics.pendingAppointments': 0
        });
      });

    // 检查咨询服务方法是否存在
    if (typeof consultService.getStaffConsultationStatistics === 'function') {
      // 获取咨询统计
      consultService.getStaffConsultationStatistics(staffId)
        .then(res => {
          this.setData({
            'statistics.totalConsultations': res.totalCount || 0,
            'statistics.activeConsultations': res.activeCount || 0,
            loading: false
          });
          wx.hideLoading();
        })
        .catch(err => {
          console.error('获取咨询统计失败', err);
          // 设置默认值，避免UI显示错误
          this.setData({
            'statistics.totalConsultations': 0,
            'statistics.activeConsultations': 0,
            loading: false
          });
          wx.hideLoading();
        });
    } else {
      console.warn('咨询统计服务不可用，使用默认值');
      this.setData({
        'statistics.totalConsultations': 0,
        'statistics.activeConsultations': 0,
        loading: false
      });
      wx.hideLoading();
    }
  },

  // 加载今日预约
  loadTodayAppointments: function () {
    const staffId = this.data.staffInfo ? this.data.staffInfo.id : null;
    if (!staffId) return;

    appointmentService.getStaffTodayAppointments(staffId)
      .then(res => {
        // 处理数据，格式化时间等
        const appointments = res.map(item => {
          return {
            ...item,
            formattedTime: util.formatTime(new Date(item.appointmentTime.replace(' ', 'T')))
          };
        });

        this.setData({
          todayAppointments: appointments
        });
      })
      .catch(err => {
        console.error('获取今日预约失败', err);
      });
  },

  // 处理头像加载错误
  onAvatarError: function(e) {
    const index = e.currentTarget.dataset.index;
    const defaultAvatarPath = '/static/images/user-default.png';
    
    // 设置默认头像
    const key = `recentConsultations[${index}].userAvatar`;
    this.setData({
      [key]: defaultAvatarPath
    });
    
    console.log(`头像加载失败，已替换为默认头像，索引: ${index}`);
  },

  // 加载最近咨询
  loadRecentConsultations: function () {
    const staffId = this.data.staffInfo ? this.data.staffInfo.id : null;
    if (!staffId) {
      console.log('没有获取到staffId，跳过加载最近咨询');
      return;
    }

    console.log('开始加载最近咨询列表，staffId:', staffId);

    // 检查方法是否存在
    if (typeof consultService.getStaffRecentConversations === 'function') {
      consultService.getStaffRecentConversations(staffId)
        .then(res => {
          console.log('获取最近咨询成功，原始数据:', res);
          
          // 处理数据，格式化时间等
          const consultations = res.map(item => {
            // 创建一个默认头像路径
            const defaultAvatarPath = '/static/images/default-avatar.png';
            
            // 确保头像地址正确
            let userAvatar = item.userAvatar || item.avatar;
            console.log(`咨询ID:${item.id} 用户:${item.userName || '用户'+item.userId} 头像:`, userAvatar);
            
            // 如果头像以/开头但没有完整域名，添加域名
            if (userAvatar && userAvatar.startsWith('/')) {
              const app = getApp();
              const baseUrl = app.globalData.baseUrl || '';
              if (baseUrl && baseUrl.startsWith('http')) {
                const baseUrlWithoutApi = baseUrl.replace(/\/api$/, '');
                userAvatar = baseUrlWithoutApi + userAvatar;
                console.log('补全头像URL:', userAvatar);
              }
            } else if (!userAvatar) {
              userAvatar = defaultAvatarPath;
              console.log('使用默认头像');
            }
            
            return {
              ...item,
              userAvatar: userAvatar,
              lastMessageTime: util.formatTime(new Date(item.lastMessageTime.replace(' ', 'T')))
            };
          });

          this.setData({
            recentConsultations: consultations
          });
          
          console.log('最近咨询数据处理完成, 共', consultations.length, '条记录');
        })
        .catch(err => {
          console.error('获取最近咨询失败:', err);
          this.setData({
            recentConsultations: []
          });
        });
    } else {
      console.warn('最近咨询服务不可用');
      this.setData({
        recentConsultations: []
      });
    }
  },

  // 跳转到预约列表
  navigateToAppointments: function () {
    wx.navigateTo({
      url: '/pages/staff/appointments/index'
    });
  },

  // 跳转到预约详情
  navigateToAppointmentDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/staff/appointments/detail?id=${id}`
    });
  },

  // 跳转到咨询列表
  navigateToConsultations: function () {
    wx.navigateTo({
      url: '/pages/staff/consults/index'
    });
  },

  // 跳转到咨询聊天
  navigateToConsultChat: function (e) {
    const id = e.currentTarget.dataset.id;
    const status = e.currentTarget.dataset.status || 0;
    wx.navigateTo({
      url: `/pages/staff/consults/chat?id=${id}&status=${status}`
    });
  },

  // 跳转到个人信息页面
  navigateToProfile: function() {
    wx.navigateTo({
      url: '/pages/staff/profile/index'
    });
  },

  // 退出登录
  logout: function () {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: res => {
        if (res.confirm) {
          getApp().clearLoginInfo();
          wx.reLaunch({
            url: '/pages/login/login'
          });
        }
      }
    });
  }
}); 